/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DepthView.java
 *   @Date: 11/29/18 3:43 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.chart;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.os.Build;
import android.os.SystemClock;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.DebugUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import java.util.Date;
import java.util.List;

import io.bhex.chart.entity.DepthData;
import io.bhex.chart.utils.MiscUtil;


public class DepthView extends View{
    private final String TAG = "DepthView";

    private Context mContext;
    //绘图区的左右上下边距
    private float marginBottom;
    private float marginLeft;
    private float marginRight;
    private float marginTop;
    //字体大小
    private float fontSize;
    //自定义view的高、宽
    private float viewHeight;
    private float viewWidth;
    //纬度高度
    private float latitudeSpacing;
    //经度宽度
    private float longitudeSpacing;
    //总根数 默认为100根
    private int mTotalCount=100;
    //    //左半屏每根线的宽度
//    private float perWidthPixelOfLeft;
//    //右半屏每根线的宽度
//    private float perWidthPixelOfRight;
    //纵向块数
    private int bgGridColumnNum = 2;
    //横向块数
    private int bgGridRowNum = 2;
    //左区路径
    private Path leftPaths;
    //右区路径
    private Path rightPaths;
    //绘图所需的实体数据集
    private DepthData depthData;
    //画布比例尺 默认是1 范围0-1
    private float canvasScale;
    //背景网格线颜色
    private int bgGridLineColor;

    //是否需要绘制背景网格
    private boolean isNeedGrid;
    //是否需要绘制十字线
    private boolean isNeedCrossLine;
    //左区折线颜色
    private int lineColorLeft;
    //填充渐变色开始颜色
    private int bgGradientStartColorLeft;
    //填充渐变色结束颜色
    private int bgGradientEndColorLeft;

    //右区折线颜色
    private int lineColorRight;
    private int bgGradientStartColorRight;
    private int bgGradientEndColorRight;
    //中间间距
    private float marginMiddle;

    //左屏根数
    private int leftCount;
    //右屏根数
    private int rightCount;
    //中间绘图区高度
    private float vHeight;
    //中间绘图区宽度
    private float vWidth;
    //字体颜色
    private int fontColor;
    //默认不是长按
    private boolean mIsLongPressed=false;
    /**触摸点坐标*/
    private float touchX;
    //画布
    private Canvas canvas;
    //是否超出了边界
    private boolean isBeyondBoundary=false;
    //X、Y轴小数位数
    private int decimalDigitsX;
    private int decimalDigitsY;
    //十字线颜色+坐标轴浮动提示文字背景区域颜色
    private int crossLineColor;
    //每X个单位所占屏幕像素
    private float perXPiexl;
    //每Y个单位所占屏幕像素
    private float perYPiexl;
    //是否显示X轴中间文本数
    private boolean isShowXMiddleTxt;
    private GestureDetectorCompat gestureDetectorCompat;
    private OnClickListener mClickLintener;
    private int fontColorOfFinger;

    public DepthView(Context context) {
        super(context);
        mContext = context;
        initView(context,null);
    }

    public DepthView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView(context,attrs);
    }

    public DepthView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView(context,attrs);
    }
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DepthView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr,defStyleRes);
        mContext = context;
        initView(context,attrs);
    }


    private void initView(Context context,AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.DepthView);
        marginLeft = typedArray.getDimension(R.styleable.DepthView_marginLeft,10);
        marginTop = typedArray.getDimension(R.styleable.DepthView_marginTop,10);
        marginRight = typedArray.getDimension(R.styleable.DepthView_marginRight,10);
        marginBottom = typedArray.getDimension(R.styleable.DepthView_marginBottom,10);
        marginMiddle = typedArray.getDimension(R.styleable.DepthView_marginMiddle,10);
        fontSize = typedArray.getDimension(R.styleable.DepthView_fontSize,10);
        fontColor = typedArray.getColor(R.styleable.DepthView_fontColor, context.getResources().getColor(R.color.white));
        fontColorOfFinger = typedArray.getColor(R.styleable.DepthView_fontColorOfFinger, context.getResources().getColor(R.color.white));
//        marginLeft = PixelUtil.dp2px(mContext,typedArray.getDimension(R.styleable.DepthView_marginLeft,10));
//        marginTop = PixelUtil.dp2px(mContext,typedArray.getDimension(R.styleable.DepthView_marginTop,10));
//        marginRight = PixelUtil.dp2px(mContext,typedArray.getDimension(R.styleable.DepthView_marginRight,10));
//        marginBottom = PixelUtil.dp2px(mContext,typedArray.getDimension(R.styleable.DepthView_marginBottom,10));
//        fontSize = PixelUtil.sp2px(mContext,typedArray.getDimension(R.styleable.DepthView_fontSize,10));
        canvasScale = typedArray.getFloat(R.styleable.DepthView_scale,1f);
        bgGridLineColor = typedArray.getColor(R.styleable.DepthView_bgGridLineColor, context.getResources().getColor(R.color.color_2c2c34));
        lineColorLeft = typedArray.getColor(R.styleable.DepthView_lineColor, context.getResources().getColor(R.color.color_528bf4));
        bgGradientStartColorLeft = typedArray.getColor(R.styleable.DepthView_gradientStartColor, context.getResources().getColor(R.color.color_000000));
        bgGradientEndColorLeft = typedArray.getColor(R.styleable.DepthView_gradientEndColor, context.getResources().getColor(R.color.color_568eff));
        crossLineColor = typedArray.getColor(R.styleable.DepthView_crossLineColor, context.getResources().getColor(R.color.color_568eff));

        lineColorRight = typedArray.getColor(R.styleable.DepthView_line2Color, context.getResources().getColor(R.color.color_528bf4));
        bgGradientStartColorRight = typedArray.getColor(R.styleable.DepthView_gradient2StartColor, context.getResources().getColor(R.color.color_000000));
        bgGradientEndColorRight = typedArray.getColor(R.styleable.DepthView_gradient2EndColor, context.getResources().getColor(R.color.color_568eff));

        isNeedGrid = typedArray.getBoolean(R.styleable.DepthView_isNeedGrid, false);
        isNeedCrossLine = typedArray.getBoolean(R.styleable.DepthView_isNeedCrossLine, false);
        bgGridRowNum = typedArray.getInteger(R.styleable.DepthView_bgGridRowNum, 2);
        bgGridColumnNum = typedArray.getInteger(R.styleable.DepthView_bgGridColumnNum, 2);
        isShowXMiddleTxt = typedArray.getBoolean(R.styleable.DepthView_isShowXMiddleTxt, true);
        decimalDigitsX = typedArray.getInteger(R.styleable.DepthView_decimalDigitsX, 2);
        decimalDigitsY = typedArray.getInteger(R.styleable.DepthView_decimalDigitsY, 2);
        typedArray.recycle();

        setWillNotDraw(false);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        //初始化数据实体
        depthData = new DepthData();
        depthData.setScale(canvasScale);
        leftPaths = new Path();
        rightPaths = new Path();
        gestureDetectorCompat = new GestureDetectorCompat(getContext(), new DepthViewGestureViewListener());


    }

    private void init() {
        leftPaths.reset();
        rightPaths.reset();
        viewHeight = getHeight();
        viewWidth = getWidth();
//        marginLeft = marginTop = marginRight = marginBottom = 10;
        vHeight = viewHeight -marginTop-marginBottom;
        vWidth = viewWidth -marginLeft-marginRight;
        latitudeSpacing = (viewHeight - marginTop - marginBottom) / bgGridRowNum;
        longitudeSpacing = (viewWidth - marginLeft - marginRight) / bgGridColumnNum;
        decimalDigitsX = depthData.getDecimalDigitsX();
        decimalDigitsY = depthData.getDecimalDigitsY();
        if (!depthData.getLeftDatas().isEmpty()) {
            leftCount = depthData.getLeftDatas().size();

        }
        if (!depthData.getRightDatas().isEmpty()) {
            rightCount = depthData.getRightDatas().size();
        }
        canvasScale = depthData.getScale();

        calPerXYPixel();
        handleData();
    }

    /**
     * 设置字体颜色
     * @param clolor
     */
    public void setFontColor(int clolor){
        fontColor = clolor;
    }

    /**
     * 设置十字线颜色
     * @param clolor
     */
    public void setCrossLineColor(int clolor){
        crossLineColor = clolor;
    }

    /**
     * 设置十字线浮动提示字体颜色
     * @param clolor
     */
    public void setFingerFontColorLineColor(int clolor){
        fontColorOfFinger = clolor;
    }

    /**
     * 设置背景网格线颜色
     * @param clolor
     */
    public void setGridLineColor(int clolor){
        bgGridLineColor = clolor;
    }

    /**
     * 设置折线颜色
     * @param
     */
    public void setBrokenLineColor(int leftBrokenLineColor,int rightBrokenLineColor){
        lineColorLeft = leftBrokenLineColor;
        lineColorRight = rightBrokenLineColor;
    }

    /**
     * 设置绘制渐变颜色
     * @param
     */
    public void setGradientColor(int leftStartGradientColor,int leftEndGradientColor,int rightStartGradientColor,int rightEndGradientColor){
        bgGradientStartColorLeft = leftStartGradientColor;
        bgGradientEndColorLeft = leftEndGradientColor;
        bgGradientStartColorRight = rightStartGradientColor;
        bgGradientEndColorRight = rightEndGradientColor;
    }



    /**
     * 处理数据
     */
    private void handleData() {
        List<DepthData.DepthItem> leftDatas = depthData.getLeftDatas();
        float startX =marginLeft;
        float endX =marginLeft;
        for (int i = 0; i < leftDatas.size(); i++) {
            DepthData.DepthItem leftData = leftDatas.get(i);
            if (i==0) {
                endX = startX + (leftData.getxData() - minXOfLeft)*perXPiexl;
                leftData.setxStart(startX);
                leftData.setxEnd(endX);
                startX = endX;
            }else{
                DepthData.DepthItem preItem = leftDatas.get(i - 1);
                endX = startX + (leftData.getxData() - preItem.getxData())*perXPiexl;
                leftData.setxStart(startX);
                leftData.setxEnd(endX);
                startX = endX;
            }

        }


        List<DepthData.DepthItem> rightDatas = depthData.getRightDatas();
        //重置一下数据算rightDatas
        startX =(minXOfRight-minXOfLeft)*perXPiexl+marginLeft;
        endX =0f;
        for (int i = 0; i < rightDatas.size(); i++) {
            DepthData.DepthItem rightData = rightDatas.get(i);
            if (i==0) {
                endX = startX + (rightData.getxData() - minXOfRight)*perXPiexl;
                rightData.setxStart(startX);
                rightData.setxEnd(endX);
                startX = endX;
            }else{
                DepthData.DepthItem preItem = rightDatas.get(i - 1);
                endX = startX + (rightData.getxData() - preItem.getxData())*perXPiexl;
                rightData.setxStart(startX);
                rightData.setxEnd(endX);
                startX = endX;
            }

        }
    }


    float maxXOfLeft=0f,minXOfLeft=Float.MAX_VALUE;
    float maxXOfRight=0f,minXOfRight=Float.MAX_VALUE;
    /**
     * 计算X Y 数据单位所占屏幕像素
     */
    private void calPerXYPixel() {
        maxXOfLeft=0f;
        minXOfLeft=Float.MAX_VALUE;
        maxXOfRight=0f;
        minXOfRight=Float.MAX_VALUE;

        List<DepthData.DepthItem> leftDatas = depthData.getLeftDatas();

        for (DepthData.DepthItem leftData : leftDatas) {
            float x = leftData.getxData();
            maxXOfLeft = x>maxXOfLeft ? x:maxXOfLeft;
            minXOfLeft = x<minXOfLeft ? x:minXOfLeft;
        }

        List<DepthData.DepthItem> rightDatas = depthData.getRightDatas();

        for (DepthData.DepthItem rightData : rightDatas) {
            float x = rightData.getxData();
            maxXOfRight = x>maxXOfRight ? x:maxXOfRight;
            minXOfRight = x<minXOfRight ? x:minXOfRight;
        }

        float maxX = maxXOfLeft >=maxXOfRight? maxXOfLeft:maxXOfRight;
        float minX = minXOfLeft<=minXOfRight? minXOfLeft:minXOfRight;
        float diff = maxX-minX;
        if (leftDatas.size()<2||rightDatas.size()<2) {
            //因为少于左右两边每边少于两条数据，则无法绘制深度图，如果左右数据尺寸少于两条,则每单位像素按照半边屏宽去计算
            perXPiexl =vWidth/2/(diff>0?diff:1);
        }else{
            perXPiexl =vWidth/(diff>0?diff:1);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
        updateView();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.canvas = canvas;
        init();
        if (isNeedGrid) {
            drawLongitudeLines(canvas);
            drawLatitudeLines(canvas);
        }
        drawLeftLines(canvas);
        drawRightLines(canvas);
        drawXText(canvas);
        drawYText(canvas);
        //绘制十字线
        if (isNeedCrossLine ) {
//            Log.e(TAG,marginLeft+"  刷新onDraw "+touchX);
            drawFingerCross(canvas);
        }
        Log.e("Depth-Data","当前时间》》》--- onDraw");
//        drawBuyAndSellRatio(canvas);
    }

    /**
     * 绘制Y轴文本
     * @param canvas
     */
    private void drawYText(Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(fontSize);
        paint.setColor(fontColor);

        //y轴绘制文案个数
        int yTextNum = bgGridRowNum+1;
        //y轴平均数 此处除以缩放比，求出画布占比最大数
        float perYData = depthData.getMaxHeight() /canvasScale / (yTextNum-1);
        //y轴文案所占像素宽度，文案x轴坐标，文案y轴坐标
        float yTextLength,x,y;
        //y轴文案
        String  yText;
        //文案内边距
        float yLeftPadding =8;
        float yTopPadding =2;
        float yBottomPadding =6;
        x = marginLeft + yLeftPadding;
        //x轴每一块的像素高度
        float perYHeight = vHeight /(yTextNum-1);
        for (int i = 0; i < yTextNum; i++) {

            yText = MiscUtil.roundFormat(perYData * i,decimalDigitsY);
            yTextLength = paint.measureText(yText);
            //由下至上绘制y轴文案
            if(i==yTextNum-1){//最后一条
                y = marginTop + fontSize +yTopPadding;
            }else{
                y = vHeight +marginTop - perYHeight * i - yBottomPadding;
            }

            drawText(canvas,yText,x,y,paint);
        }

    }

    /**
     * 绘制X轴文本
     * @param canvas
     */
    private void drawXText(Canvas canvas) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(fontColor);
        List<DepthData.DepthItem> leftDatas = depthData.getLeftDatas();
        float maxXOfLeft=0f,minXOfLeft= MiscUtil.roundFormatFloat(Float.MAX_VALUE,decimalDigitsX);
        //纠偏数据，如果集合数据为零 坐标默认0零
        if (leftDatas == null||leftDatas.size()<1) {
            minXOfLeft= 0f;
        }
        for (DepthData.DepthItem leftData : leftDatas) {
            float x = leftData.getxData();
            maxXOfLeft = x>maxXOfLeft ? x:maxXOfLeft;
            minXOfLeft = x<minXOfLeft ? x:minXOfLeft;
        }

//        Log.e("Depth",viewHeight + ":"+ vHeight +"  "+viewWidth +":"+vWidth);

        List<DepthData.DepthItem> rightDatas = depthData.getRightDatas();
        float maxXOfRight=0f,minXOfRight=MiscUtil.roundFormatFloat(Float.MAX_VALUE,decimalDigitsX);
        //纠偏数据，如果集合数据为零 坐标默认0零
        if (rightDatas == null||rightDatas.size()<1) {
            minXOfRight= 0f;
        }
        for (DepthData.DepthItem rightData : rightDatas) {
            float x = rightData.getxData();
            maxXOfRight = x>maxXOfRight ? x:maxXOfRight;
            minXOfRight = x<minXOfRight ? x:minXOfRight;
        }
        //x轴文案个数 因为最终将是两个文案数，所以定出规则 个数 +2  碰到奇数个列数 个数+3或者+1
        int xTextNum = bgGridColumnNum % 2 == 0 ? bgGridColumnNum +2 : bgGridColumnNum +3;
        float perXLeft =(maxXOfLeft-minXOfLeft)/(xTextNum/2-1);
        float perXRight =(maxXOfRight-minXOfRight)/(xTextNum/2-1);
        //TODO 纠正左右相等
//        perXLeft = perXRight = (maxXOfRight-minXOfLeft)/(xTextNum-2);

        float perXWidth = vWidth / (xTextNum -2);
//        Log.e("Depth",perXWidth + ":{"+ perXLeft+","+perXRight+"}");
        String xText;
        float xTextLength,x,y;
        float xLeftPadding=8,xRightPadding = 8;
        y = vHeight + marginTop + fontSize;
        //绘制左半部文案
        int xLeftTextNum = xTextNum/2;
        for (int i = 0; i < xLeftTextNum; i++) {
            xText = MiscUtil.roundFormat(minXOfLeft + perXLeft *i,decimalDigitsX);
            xTextLength = paint.measureText(xText);
            if (i==0){
                x = marginLeft + xLeftPadding;
            }else if (i==xLeftTextNum-1){
                x = marginLeft + perXWidth *i -xTextLength-xRightPadding;
            }else{
                x = marginLeft + perXWidth *i -xTextLength/2;
            }
            if (!isShowXMiddleTxt&&i==xLeftTextNum-1&&xLeftTextNum>1) {
            }else{
                drawText(canvas,xText,x,y,paint);
//            Log.e("Depth",x + ":"+ y);
            }
        }

        //绘制右半部文案
        int xRightTextNum = xTextNum/2;
        for (int i = 0; i < xRightTextNum; i++) {
            xText = MiscUtil.roundFormat(minXOfRight + perXRight *i,decimalDigitsX);
            xTextLength = paint.measureText(xText);
            if (i==0){
                x = marginLeft + vWidth/2 +xLeftPadding;
            }else if (i==xRightTextNum-1){
                x = marginLeft + vWidth/2 + perXWidth *i -xTextLength-xRightPadding;
            }else{
                x = marginLeft + vWidth/2  + perXWidth *i -xTextLength/2;
            }
            //至少保留一条x轴坐标数据
            if (!isShowXMiddleTxt&&i==0&&xRightTextNum>1) {
            }else{
                drawText(canvas,xText,x,y,paint);
//            Log.e("Depth",x + ":"+ y);
            }
        }

    }

    /**
     * 绘制经线 竖线
     */
    private void drawLongitudeLines(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(bgGridLineColor);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(2f);

        for (int i = 0; i < bgGridColumnNum + 1; i++) {
            //分时
            canvas.drawLine(marginLeft + longitudeSpacing * i,
                    marginTop, marginLeft + longitudeSpacing * i, viewHeight - marginBottom,
                    paint);
        }

    }

    /**
     * 绘制纬线 横线
     * TODO 每根线的起点代表  目前是以每根线宽度的结束点去开始绘制
     */
    private void drawLatitudeLines(Canvas canvas) {

        Paint paint = new Paint();
        paint.setColor(bgGridLineColor);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(2f);

        for (int i = 0; i < bgGridRowNum + 1; i++) {
            canvas.drawLine(marginLeft,
                    marginTop + latitudeSpacing * i, viewWidth - marginRight, marginTop + latitudeSpacing * i,
                    paint);
        }
    }

    //画分时线 渐变色
    private void drawLeftLines(Canvas canvas) {
        Paint mPaintLine = new Paint();
        //mPaintLine.setStrokeWidth((float) pixelPerMinute);
        mPaintLine.setStrokeWidth(2f);
        mPaintLine.setAntiAlias(true);
//        mPaintLine.setStrokeJoin(Paint.Join.ROUND);
//        mPaintLine.setPathEffect(new CornerPathEffect(200));
        mPaintLine.setColor(lineColorLeft);

        //定义路径的起点
        leftPaths.moveTo(marginLeft, viewHeight-marginBottom);

        float maxHeight = depthData.getMaxHeight();
        float vHeight = viewHeight - marginTop - marginBottom;
        List<DepthData.DepthItem> datas = depthData.getLeftDatas();
        float currentX,endX=0f;
        float currentY;
        for (int i = 0; i < datas.size(); i++) {
            DepthData.DepthItem data = datas.get(i);
//            Log.e("TEST",i+": "+data.getxStart()+" "+data.getxEnd());
            if (data != null) {
                currentX = data.getxStart();
                if (i==0) {
                    //绘制L的横线
                    float yHeight = data.getyData()/ maxHeight * vHeight * canvasScale;
                    currentY = viewHeight - marginBottom - yHeight;
                    canvas.drawLine(currentX, currentY, data.getxEnd(), currentY, mPaintLine);
                    leftPaths.lineTo(currentX,currentY);
                    leftPaths.lineTo(data.getxEnd(), currentY);
                }else{

                    DepthData.DepthItem preItem = datas.get(i - 1);
                    float yHeightPre = preItem.getyData()/ maxHeight * vHeight * canvasScale;
                    float preY = viewHeight - marginBottom - yHeightPre;
                    float yHeight = data.getyData()/ maxHeight * vHeight * canvasScale;
                    currentY = viewHeight - marginBottom - yHeight;

                    //绘制L的竖线
                    canvas.drawLine(preItem.getxEnd(), preY, preItem.getxEnd(), currentY, mPaintLine);

                    //绘制L的横线
                    canvas.drawLine(currentX, currentY, data.getxEnd(),currentY, mPaintLine);
                    leftPaths.lineTo(preItem.getxEnd(), preY);
                    leftPaths.lineTo(currentX,currentY);

                    if (i==datas.size()-1){
                        leftPaths.lineTo(data.getxEnd(),currentY);
                    }
                }
                endX = data.getxEnd();
            }
        }

        //路径的最后一个点
        leftPaths.lineTo(endX,viewHeight-marginBottom);
        leftPaths.close();
        //渐变色颜色填充
        LinearGradient gradient = new LinearGradient(marginLeft, vHeight, marginLeft,
                vHeight*(1-canvasScale), bgGradientStartColorLeft, bgGradientEndColorLeft, Shader.TileMode.MIRROR);
        mPaintLine.setShader(gradient);

        canvas.drawPath(leftPaths, mPaintLine);
    }

    //画分时线 渐变色
    private void drawRightLines(Canvas canvas) {
        Paint mPaintLine = new Paint();
        mPaintLine.setStrokeWidth(2f);
        mPaintLine.setAntiAlias(true);
        mPaintLine.setColor(lineColorRight);

        float maxHeight = depthData.getMaxHeight();
        float vHeight = viewHeight - marginTop - marginBottom;
        List<DepthData.DepthItem> datas = depthData.getRightDatas();
        float currentX,endX=0f;
        float currentY;
        for (int i = 0; i < datas.size(); i++) {
            DepthData.DepthItem data = datas.get(i);
//            Log.e("TEST",i+": "+data.getxStart()+" "+data.getxEnd());
            if (data != null) {
                currentX = data.getxStart();
                if (i==0) {
                    //绘制L的横线
                    float yHeight = data.getyData()/ maxHeight * vHeight * canvasScale;
                    currentY = viewHeight - marginBottom - yHeight;
                    canvas.drawLine(currentX, currentY, data.getxEnd(), currentY, mPaintLine);
                    //定义路径的起点
                    rightPaths.moveTo(currentX, viewHeight-marginBottom);
                    rightPaths.lineTo(currentX,currentY);
                    rightPaths.lineTo(data.getxEnd(), currentY);
                }else{

                    //绘制L的竖线
                    DepthData.DepthItem preItem = datas.get(i - 1);
                    float yHeightPre = preItem.getyData()/ maxHeight * vHeight * canvasScale;
                    float preY = viewHeight - marginBottom - yHeightPre;
                    //绘制L的横线
                    float yHeight = data.getyData()/ maxHeight * vHeight * canvasScale;
                    currentY = viewHeight - marginBottom - yHeight;

                    canvas.drawLine(preItem.getxEnd(), preY, preItem.getxEnd(), currentY, mPaintLine);

                    canvas.drawLine(currentX, currentY, data.getxEnd(),currentY, mPaintLine);
                    rightPaths.lineTo(preItem.getxEnd(), preY);
                    rightPaths.lineTo(currentX,currentY);

                    if (i==datas.size()-1){
                        rightPaths.lineTo(data.getxEnd(),currentY);
                    }

                }
                endX = data.getxEnd();
            }
        }

        //路径的最后一个点
        rightPaths.lineTo(endX,viewHeight-marginBottom);


        //渐变色颜色填充
        LinearGradient gradient = new LinearGradient(viewWidth-marginRight, viewHeight-marginBottom, viewWidth-marginRight,
                vHeight*(1-canvasScale)+marginTop, bgGradientStartColorRight, bgGradientEndColorRight, Shader.TileMode.MIRROR);
        mPaintLine.setShader(gradient);

        canvas.drawPath(rightPaths, mPaintLine);
    }

    /**
     * 绘制文本
     * @param canvas
     * @param text
     * @param x
     * @param y
     */
    public void drawText(Canvas canvas,String text,float x,float y,Paint paint){

        canvas.drawText(text,x,y,paint);
    }


    private float lastX = 0.0f;
    private float lastY = 0.0f;
    private long  lastTime = 0l;
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:{
                lastX = event.getX();
                lastY = event.getY();
                lastTime = System.currentTimeMillis();
                isBeyondBoundary = false;
            }
            break;

            case MotionEvent.ACTION_MOVE:
            {
                float thisX = event.getX();
                float thisY = event.getY();
                long thisTime =  System.currentTimeMillis();
                if(!mIsLongPressed){
                    mIsLongPressed = isLongPressed(lastX, lastY, thisX, thisY, lastTime, thisTime,300L);
                }
                touchX = mIsLongPressed?thisX:touchX;
                if (!isBeyondXBoundary(touchX)) {
//                    Log.e(TAG,marginLeft+"  刷新 "+touchX);
                    postInvalidate();
                }
//                drawFingerCross(canvas);
            }
            break;
            case MotionEvent.ACTION_UP:
                mIsLongPressed = false;
                isBeyondBoundary = false;
//                changeWindow.changeWindow(KlineConstants.DIRECTION_RIGHT,KlineConstants.View_GONE,null);
//                postInvalidate();
                drawFingerCross(canvas);
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                break;
        }
        gestureDetectorCompat.onTouchEvent(event);
        return true;
    }

    //是否超出X轴边界
    private boolean isBeyondXBoundary(float touchX) {
        if (touchX<marginLeft||touchX>viewWidth-marginRight){
            isBeyondBoundary = true;
            return true;
        }else {
            return false;
        }
    }

    /**长按事件*/
    private boolean isLongPressed(float lastX,float lastY,
                                  float thisX,float thisY,
                                  long lastDownTime,long thisEventTime,
                                  long longPressTime){
        float offsetX = Math.abs(thisX - lastX);
        float offsetY = Math.abs(thisY - lastY);
        long intervalTime = thisEventTime - lastDownTime;
        return intervalTime >= longPressTime;
    }

    //绘制十字线
    private void drawFingerCross(Canvas canvas){
        /* 长按事件 */
        if(mIsLongPressed&&isNeedCrossLine){
            //超过边界就不在绘制
            if (touchX<marginLeft||touchX>viewWidth-marginRight){
                return;
            }

            canvas.restore();

            Paint paint = new Paint();
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(crossLineColor);
            paint.setStrokeWidth(3f);
            paint.setAntiAlias(false);
            paint.setDither(false);
            paint.setTextSize(fontSize);


            float middlePointLeft = vWidth/2 - marginMiddle/2+marginLeft;
            float middlePointRight = vWidth/2 + marginMiddle/2+marginLeft;
            if (touchX>middlePointLeft&&touchX<middlePointRight){
                return;
            }

            //当前手指出点所处位置 左 中 右
            final int pointLeft=-1,pointMiddle =0,pointRight =1;
            int currentPoint;
            if (touchX<=middlePointLeft){
                currentPoint = pointLeft;
            }else if(touchX>=middlePointRight){
                currentPoint = pointRight;
            }else{
                currentPoint = pointMiddle;
            }
            float x,y;
            //当前所处的那一根数据
            DepthData.DepthItem currentDepthItem=null;
            switch (currentPoint){
                //左边区域
                case pointLeft:
                    currentDepthItem = calCurrentItem(true,touchX);
//                    int index = MiscUtil.roundFormatFloat(((touchX-marginLeft)/perWidthPixelOfLeft),0,BigDecimal.ROUND_UP);
//                    Log.e("Depth", "Index: "+(touchX-marginLeft)/perWidthPixelOfLeft+"  "+index);
//                    index = index>0?index-1:0;
//                    int size = depthData.getLeftDatas().size();
//                    index= index>=size?size-1:index;
//                    currentDepthItem = depthData.getLeftDatas().get(index);
                    break;
                //中间区域
                case pointMiddle:

                    break;
                //右边区域
                case pointRight:
                    currentDepthItem = calCurrentItem(false,touchX);
//                    int indexRight = MiscUtil.roundFormatFloat((touchX-middlePointRight)/perWidthPixelOfRight,0,BigDecimal.ROUND_UP);
//                    Log.e("Depth", "Index: "+(touchX-middlePointRight)/perWidthPixelOfRight+"  "+indexRight);
//                    indexRight = indexRight>0?indexRight-1:0;
//                    int sizeRight = depthData.getRightDatas().size();
//                    indexRight= indexRight>=sizeRight?sizeRight-1:indexRight;
//                    currentDepthItem = depthData.getRightDatas().get(indexRight);
                    break;
            }
            x = touchX;
            if (currentDepthItem != null) {

                float perHeight = currentDepthItem.getyData()/ depthData.getMaxHeight() * vHeight * canvasScale;
                y = viewHeight - marginBottom - perHeight;
                /**垂直线---分时--成交量*/
                Path path = new Path();
//                path.moveTo(x, marginTop);
//                path.lineTo(x, viewHeight-marginBottom);
                //PathEffect effects = new DashPathEffect(new float[]{5,5,5,5},1);
                //PathEffect effect = new DashPathEffect(new float[] { 1, 2, 4, 8}, 1);
                //画虚线
//                paint.setPathEffect(new DashPathEffect(new float[] { 1, 2, 4, 8}, 1));
                //paint.setPathEffect(effects);
                //canvas.drawPath(path, paint);
                canvas.drawLine(x, marginTop, x, viewHeight-marginBottom, paint);
                /**水平线*/
//                path.moveTo(marginLeft, y);
//                path.lineTo(viewWidth-marginRight, y);
//                canvas.drawPath(path, paint);
                canvas.drawLine(marginLeft, y, viewWidth-marginRight, y,paint);

                /**绘制x轴文案方块提示*/
                String xData = MiscUtil.roundFormat(currentDepthItem.getxData(),decimalDigitsX);
                float xDataLength = paint.measureText(xData);
                paint.setStyle(Paint.Style.FILL);
                float rectTextFontSize = fontSize+2;
                paint.setTextSize(rectTextFontSize);
                paint.setColor(crossLineColor);

                float rectXLeft = x-xDataLength/2>marginLeft?x-xDataLength/2:marginLeft;
                //判断绘制超边界问题
                if (x-xDataLength/2>viewWidth-marginRight-xDataLength){
                    rectXLeft = viewWidth-marginRight-xDataLength;
                }
                float rectXRight = x+xDataLength/2<viewWidth-marginRight?x+xDataLength/2:viewWidth-marginRight;
                if (x+xDataLength/2<marginLeft+xDataLength){
                    rectXRight = marginLeft+xDataLength;
                }
                canvas.drawRect(rectXLeft-5,viewHeight-marginBottom,rectXRight+10,viewHeight-marginBottom+rectTextFontSize+5,paint);
                float textX;
                //判断绘制超边界问题
                textX = x-xDataLength/2<marginLeft?marginLeft:x-xDataLength/2;
                textX = textX>viewWidth-marginRight-xDataLength? viewWidth-marginRight-xDataLength:textX;
                paint.setColor(fontColorOfFinger);
                canvas.drawText(xData,textX,viewHeight-marginBottom+rectTextFontSize,paint);

                /**绘制Y轴方块以及文案*/
                String yData = MiscUtil.roundFormat(currentDepthItem.getyData(),decimalDigitsY);
                float yDataLength = paint.measureText(yData);
                paint.setStyle(Paint.Style.FILL);
                paint.setTextSize(rectTextFontSize);
                paint.setColor(crossLineColor);
                float rectYLeft,rectYTop,rectYRight,rectYBottom;
                float textYx,textYy;
                if(x>vWidth/2+marginLeft){//左边
                    rectYLeft = marginLeft;
                    rectYTop = y-rectTextFontSize/2;
                    rectYRight = marginLeft+yDataLength;
                    rectYBottom = y+rectTextFontSize/2;

                    textYx = marginLeft;
                    textYy = y+rectTextFontSize/2;
                }else{
                    rectYLeft = viewWidth-marginRight-yDataLength;
                    rectYTop = y-rectTextFontSize/2;
                    rectYRight = viewWidth-marginRight;
                    rectYBottom = y+rectTextFontSize/2;

                    textYx = viewWidth-marginRight-yDataLength;
                    textYy = y+rectTextFontSize/2;
                }

                //超边界绘制的判断
                if(y<marginTop+rectTextFontSize/2){
                    rectYTop = marginTop;
                    rectYBottom = marginTop+rectTextFontSize;
                }

                if(rectYTop > viewHeight-marginBottom-rectTextFontSize){
                    rectYTop = viewHeight-marginBottom-rectTextFontSize;
                    rectYBottom = viewHeight-marginBottom;
                }
                //文字矩形背景
                canvas.drawRect(rectYLeft-5,rectYTop,rectYRight+5,rectYBottom+5,paint);


                //判断绘制超边界问题
                if(textYy<marginTop+rectTextFontSize){
                    textYy = marginTop+rectTextFontSize;
                }

                if (textYy>viewHeight-marginBottom){
                    textYy = viewHeight-marginBottom;
                }
                //绘制提示文字
                paint.setColor(fontColorOfFinger);
                canvas.drawText(yData,textYx,textYy,paint);
            }else{
                Log.e(TAG,"x："+x +"  marginLeft:"+marginLeft +" marginRight:"+marginRight);
            }
        }

    }

    /**
     * 计算当前移动到了那个item实体上面
     * @param touchX
     */
    private DepthData.DepthItem calCurrentItem(boolean isLeft,float touchX) {
        if (isLeft) {
            List<DepthData.DepthItem> leftDatas = depthData.getLeftDatas();
            for (DepthData.DepthItem leftData : leftDatas) {
                float xStart = leftData.getxStart();
                float xEnd = leftData.getxEnd();

                if (xStart <=touchX&&touchX<xEnd){
                    return leftData;
                }
            }
        }else{
            List<DepthData.DepthItem> rightDatas = depthData.getRightDatas();
            for (DepthData.DepthItem rightData : rightDatas) {
                float xStart = rightData.getxStart();
                float xEnd = rightData.getxEnd();

                if (xStart<=touchX&&touchX<xEnd){
                    return rightData;
                }
            }
        }

        return null;

    }


    /**
     * 绘制买卖比例图 （顶部中间）
     * @param canvas
     */
    private void drawBuyAndSellRatio(Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(2f);
        paint.setTextSize(fontSize);
        paint.setColor(fontColor);
        List<DepthData.DepthItem> leftDatas = depthData.getLeftDatas();
        List<DepthData.DepthItem> rightDatas = depthData.getRightDatas();

        //绘制顶部最接近的左右数据值
        if (!leftDatas.isEmpty()){

            String leftXText =MiscUtil.roundFormat(leftDatas.get(leftDatas.size()-1).getxData(),decimalDigitsX);
            float leftXTextLength = paint.measureText(leftXText);
            drawText(canvas,leftXText,marginLeft+vWidth/2- leftXTextLength-marginMiddle/2,marginTop+fontSize+5,paint);
        }
        if (!rightDatas.isEmpty()) {
            String rightXText =MiscUtil.roundFormat(rightDatas.get(0).getxData(),decimalDigitsX);
            drawText(canvas,rightXText,marginLeft+vWidth/2+marginMiddle/2,marginTop+fontSize+5,paint);
        }

        //计算中间最接近数值比 公式：(b-a)/(（a+b)/2)
        if (!leftDatas.isEmpty()&&!rightDatas.isEmpty()) {
            float a = leftDatas.get(leftDatas.size() - 1).getxData();
            float b = rightDatas.get(rightDatas.size() - 1).getxData();
            //百分比 默认两位小数点
            String ratioValue = MiscUtil.roundFormat((b - a) / ((a+b) / 2) / 100, 2) + "%";
            float valueLength = paint.measureText(ratioValue);

            float middleXPoint = vWidth / 2 + marginLeft;
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(crossLineColor);
            float lineWidth = valueLength + 20f;
            float lineHeight = 10f;
            //定义中间横线的坐标
            float startX = middleXPoint - lineWidth / 2;
            float stopX = middleXPoint + lineWidth / 2;
            float startY = marginTop + 100f;
            float stopY = startY;
            //中间横线
            canvas.drawLine(startX, startY, stopX, stopY, paint);
            //左竖线
            canvas.drawLine(startX, startY - lineHeight, startX, stopY, paint);
            //右竖线
            canvas.drawLine(stopX, stopY - lineHeight, stopX, stopY, paint);

            //绘制中间最接近数值比 公式：(b-a)/(（a+b)/2)
            paint.setColor(fontColor);

            canvas.drawText(ratioValue, middleXPoint - valueLength / 2, stopY - 5, paint);
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = (int) ev.getRawX();
        int y = (int) ev.getRawY();
        int dealtX = 0;
        int dealtY = 0;

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dealtX = 0;
                dealtY = 0;
                // 保证子View能够接收到Action_move事件
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                dealtX += Math.abs(x - lastX);
                dealtY += Math.abs(y - lastY);
                Log.i(TAG, "dealtX:=" + dealtX);
                Log.i(TAG, "dealtY:=" + dealtY);
                // 这里是够拦截的判断依据是左右滑动，读者可根据自己的逻辑进行是否拦截
//                if (dealtX >= dealtY) {
                if (mIsLongPressed) {
                    //长安状态下  先请求 父 View不要拦截事件
                    getParent().requestDisallowInterceptTouchEvent(true);
                } else {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_UP:
                getParent().requestDisallowInterceptTouchEvent(false);
                break;

        }
        return super.dispatchTouchEvent(ev);
    }

    //设置绘制比例尺
    public void setScale(float scale){
        depthData.setScale(scale);
        updateView();
    }


    //设置绘制比例尺
    public float getScale(){
        return canvasScale;
    }

    long lastTimet = System.currentTimeMillis();
    //更新View
    private void updateView() {
        long currentTimet = System.currentTimeMillis();
        updateConfig();
        if(currentTimet-lastTimet>100){
            //Log.d("DepthView:","datasOfLeft:"+depthData.getLeftDatas().size()+" datasOfRight:"+depthData.getRightDatas().size());
//        Log.e(TAG,marginLeft+"  刷新updateView "+touchX);

        }
        //Log.d("DepthView:","mContext:"+mContext.getClass().getName());

        //Log.d("BaseTradeFragment:","Thread==2:"+Thread.currentThread().getName());
        postInvalidate();
        lastTimet = currentTimet;

    }

    //更新配置参数
    private void updateConfig() {
        canvasScale = depthData.getScale();
        leftCount = depthData.getLeftDatas().size();
//        leftCount = mTotalCount%2==0?mTotalCount/2:(mTotalCount-1)/2;
        rightCount = mTotalCount -leftCount;

        calPerXYPixel();
        handleData();
    }

    /**
     * 设置X Y轴小数点个数
     * @param x
     * @param y
     */
    public void setDecimalDigits(int x,int y){
        depthData.setMaxHeight(0);
        depthData.setDecimalDigitsX(x);
        depthData.setDecimalDigitsY(y);
    }

    //设置深度左数据
    public void setLeftData(List<DepthData.DepthItem> datas){
        depthData.setLeftDatas(datas);
        updateView();
    }

    //添加单条深度左数据
    public void addLeftData(DepthData.DepthItem item){
        depthData.addLeftItem(item);
        updateView();
    }

    //添加多条深度左数据
    public void addLeftDataList(List<DepthData.DepthItem> datas){
        depthData.addLeftItemList(datas);
        updateView();
    }


    //设置深度右数据
    public void setRightData(List<DepthData.DepthItem> datas){
        depthData.setRightDatas(datas);
        updateView();
    }

    //添加单条深度右数据
    public void addRightData(DepthData.DepthItem item){
        depthData.addRightItem(item);
        updateView();
    }

    //添加多条深度右数据
    public void addRightDataList(List<DepthData.DepthItem> datas){
        depthData.addRightItemList(datas);
        updateView();
    }

    /**
     * 设置点击事件
     * @param lintener
     */
    public void setOnClickLintener(OnClickListener lintener){
        mClickLintener = lintener;
    }

    /**
     * 更新深度图
     * @param depthLeftItems
     * @param depthRightItems
     */
    public void setData(List<DepthData.DepthItem> depthLeftItems, List<DepthData.DepthItem> depthRightItems) {
        Log.e("Depth-Data","当前时间》》》 start");
        depthData = new DepthData();
        depthData.setScale(canvasScale);
        depthData.setLeftDatas(depthLeftItems);
        depthData.setRightDatas(depthRightItems);
        updateView();
        Log.e("Depth-Data","当前时间》》》 end");
    }

    class DepthViewGestureViewListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (mClickLintener != null) {
                mClickLintener.onClick(DepthView.this);
            }
            return true;
        }
    }

    public interface OnClickListener{
        void onClick(View view);
    }
}
